from django.shortcuts import render
from rest_framework import viewsets
from django.db.models import Q, Count, F, Sum
from django.utils import timezone
from .serializers import HomeIndexSerializer
from django.db.models.functions import TruncDate
from datetime import timedelta
from medias.models import AccountBindMediaContent, MediaContent
from user.models import User
from platefrom.models import Platefrom, SkusUser
from rest_framework.decorators import action
# from .serializers import CompanySerializer,DepartmentSerializer
from utils.response_util import VueAPIResponse, APIResponse
from utils.pagination_util import PageNumberPaginationUtil
# Create your views here.
from server.utils import check_group_id
from rest_framework.decorators import permission_classes
from rest_framework.permissions import AllowAny


# Create your views here.
class HomeIndexViewSet(viewsets.ModelViewSet):
    queryset = AccountBindMediaContent.objects.all()
    serializer_class = HomeIndexSerializer
    pagination_class = PageNumberPaginationUtil

    def get_daily_data_counts(self, model, start_date, end_date):
        # 获取日期范围内的数据
        data = model.objects.filter(add_time__range=[start_date, end_date]).values('add_time')

        # 统计每天的数据数量
        data = data.annotate(count=Count('id')).order_by('add_time')

        # 初始化一个字典，用于存储每天的数据数量，没有数据的日期数量设置为0
        daily_data_counts = {str(start_date + timedelta(days=i)): 0 for i in range((end_date - start_date).days + 1)}

        # 将查询到的数据更新到字典中
        for item in data:
            date_str = item['add_time'].strftime('%Y-%m-%d')
            daily_data_counts[date_str] = item['count']

        return daily_data_counts

    def list(self, request, *args, **kwargs):
        # 媒体发布
        medias_release_queryset = self.queryset.all().order_by('id')
        # 发布成功数量
        medias_release_count = medias_release_queryset.filter(status=3).count()
        # 总发布数量
        medias_release_all_count = medias_release_queryset.count()

        # 注册用户
        user_queryset = User.objects.filter(is_superuser='0')
        user_count = user_queryset.count()
        # 认证用户
        user_auth_count = user_queryset.filter(is_auth='1').count()
        # 未认证用户
        user_no_auth_count = user_queryset.filter(is_auth='0').count()
        # 冻结用户
        user_freeze_count = user_queryset.filter(is_auth='-1').count()

        # 开通平台
        platefrom_queryset = Platefrom.objects.all()
        platefrom_sku_count = platefrom_queryset.count()

        # 套餐订单
        sku_user_queryset = SkusUser.objects.all()
        sku_user_count = sku_user_queryset.count()

        result = {
            "medias_release_all_count": medias_release_all_count,
            "medias_release_count": medias_release_count,
            "user_count": user_count,
            "user_auth_count": user_auth_count,
            "user_no_auth_count": user_no_auth_count,
            "user_freeze_count": user_freeze_count,
            "platefrom_sku_count": platefrom_sku_count,
            "sku_user_count": sku_user_count,
        }

        return APIResponse(results=result)

    @action(methods=['get'], detail=False, url_path='chart_data')
    def chart_data(self, request, *args, **kwargs):
        # 获取过去一周的第一天和最后一天的日期
        today = timezone.now().date()
        # 获取过去一周的数据数量
        weekly_data_counts = self.get_daily_data_counts(AccountBindMediaContent, today - timedelta(days=7), today)

        # 获取过去三十天的数据数量
        monthly_data_counts = self.get_daily_data_counts(AccountBindMediaContent, today - timedelta(days=30), today)

        # 可以将数据用于其他逻辑处理，例如在模板中显示
        chart_data = {
            'weekly_data': weekly_data_counts,
            'monthly_data': monthly_data_counts,
        }

        result = {
            "chart_data": chart_data,
        }

        return APIResponse(results=result)

    @action(methods=['get'], detail=False, url_path='personal')
    def personal(self, request, *args, **kwargs):
        # 媒体发布
        media_content_queryset = MediaContent.objects.filter(creator_user_id=self.request.user.id).values('id')
        medias_release_queryset = AccountBindMediaContent.objects.filter(media_content__in=media_content_queryset)
        serializer = self.get_serializer(medias_release_queryset, many=True)

        # douyin
        personalData = []
        personalData.append({"id": '1', 'title': '抖音', 'nums': 0, 'totalnums': 0, 'icon': '',"platform_name":'douyin'})
        personalData.append({"id": '2', 'title': '哔哩哔哩', 'nums': 0, 'totalnums': 0, 'icon': '',"platform_name":'bilibili'})
        personalData.append({"id": '3', 'title': '快手', 'nums': 0, 'totalnums': 0, 'icon': '',"platform_name":'kuaishou'})
        personalData.append({"id": '4', 'title': '小红书', 'nums': 0, 'totalnums': 0, 'icon': '',"platform_name":'xiaohongshu'})

        medias_release_all_count = 0
        medias_release_count = 0

        views_all_count = 0
        likes_all_count = 0
        collect_all_count = 0


        for item in serializer.data:
            medias_release_all_count += 1
            views_all_count += item['views_count'] if item['views_count'] is not None else 0
            likes_all_count += item['likes_count'] if item['likes_count'] is not None else 0
            collect_all_count += item['collect_count'] if item['collect_count'] is not None else 0
            for plate in personalData:
                if item['platform_name'] == plate['platform_name']:
                    if item['status'] == 3:
                        medias_release_count += 1
                        plate['totalnums'] = plate['totalnums'] + 1
                        plate['nums'] = plate['nums'] + 1
                    else:
                        plate['totalnums'] = plate['totalnums'] + 1

        # # 浏览总量
        # views_all_count = \
        # AccountBindMediaContent.objects.all().filter(media_content__in=media_content_queryset).aggregate(
        #     total=Sum('views_count'))['total']
        #
        # # 点赞总量
        # likes_all_count = AccountBindMediaContent.objects.filter(media_content__in=media_content_queryset).aggregate(
        #     total=Sum('likes_count'))['total']
        #
        # # 浏览总量
        # collect_all_count = AccountBindMediaContent.objects.filter(media_content__in=media_content_queryset).aggregate(
        #     total=Sum('collect_count'))['total']

        # 浏览量排行
        views_count = AccountBindMediaContent.objects.filter(media_content__in=media_content_queryset).order_by(
            '-views_count').values()[:7]

        # 点赞排行
        likes_count = AccountBindMediaContent.objects.filter(media_content__in=media_content_queryset).order_by(
            '-likes_count').values()[:7]

        # 收藏排行
        collect_count = AccountBindMediaContent.objects.filter(media_content__in=media_content_queryset).order_by(
            '-collect_count').values()[:7]

        # 获取过去一周的第一天和最后一天的日期
        today = timezone.now().date()
        # 获取过去一周的数据数量
        start_week_date = today - timedelta(days=7)
        end_week_date = today
        data = AccountBindMediaContent.objects.filter(media_content__in=media_content_queryset,
                                                      add_time__range=[start_week_date, end_week_date]).values(
            'add_time')

        # 统计每天的数据数量
        data = data.annotate(count=Count('id')).order_by('add_time')

        # 初始化一个字典，用于存储每天的数据数量，没有数据的日期数量设置为0
        weekly_data_counts = {str(start_week_date + timedelta(days=i)): 0 for i in
                              range((end_week_date - start_week_date).days + 1)}

        # 将查询到的数据更新到字典中
        for item in data:
            date_str = item['add_time'].strftime('%Y-%m-%d')
            weekly_data_counts[date_str] = item['count']

        # 获取过去一个月的数据数量
        start_month_date = today - timedelta(days=30)
        end_month_date = today
        data = AccountBindMediaContent.objects.filter(media_content__in=media_content_queryset,
                                                      add_time__range=[start_month_date, end_month_date]).values(
            'add_time')

        # 统计每天的数据数量
        data = data.annotate(count=Count('id')).order_by('add_time')

        # 初始化一个字典，用于存储每天的数据数量，没有数据的日期数量设置为0
        monthly_data_counts = {str(start_month_date + timedelta(days=i)): 0 for i in
                               range((end_month_date - start_month_date).days + 1)}

        # 将查询到的数据更新到字典中
        for item in data:
            date_str = item['add_time'].strftime('%Y-%m-%d')
            monthly_data_counts[date_str] = item['count']

        # 可以将数据用于其他逻辑处理，例如在模板中显示
        chart_data = {
            'weekly_data': weekly_data_counts,
            'monthly_data': monthly_data_counts,
        }


        result = {
            "medias_release_all_count": medias_release_all_count,
            "medias_release_count": medias_release_count,
            "views_all_count": views_all_count,
            "likes_all_count": likes_all_count,
            "collect_all_count": collect_all_count,
            "views_count": views_count,
            "likes_count": likes_count,
            "collect_count": collect_count,
            "personalData": personalData,
            "chart_data": chart_data,
        }

        return APIResponse(results=result)

    @action(methods=['get'], detail=False, url_path='company_admin')
    def company_admin(self, request, *args, **kwargs):

        # 公司用户数量
        comapny_all_user = User.objects.filter(company_id=self.request.user.company_id).values()
        comapny_all_user_count = len(comapny_all_user)

        ids = comapny_all_user.values_list('id')

        # 媒体发布
        media_content_queryset = MediaContent.objects.filter(creator_user_id__in=ids).values()
        media_content_ids = media_content_queryset.values_list('id')
        medias_release_queryset = AccountBindMediaContent.objects.filter(media_content__in=media_content_ids)
        serializer = self.get_serializer(medias_release_queryset, many=True)

        # douyin
        companyAdminData = []
        companyAdminData.append(
            {"id": '1', 'title': '抖音', 'nums': 0, 'totalnums': 0, 'icon': '', "platform_name": 'douyin'})
        companyAdminData.append(
            {"id": '2', 'title': '哔哩哔哩', 'nums': 0, 'totalnums': 0, 'icon': '', "platform_name": 'bilibili'})
        companyAdminData.append(
            {"id": '3', 'title': '快手', 'nums': 0, 'totalnums': 0, 'icon': '', "platform_name": 'kuaishou'})
        companyAdminData.append(
            {"id": '4', 'title': '小红书', 'nums': 0, 'totalnums': 0, 'icon': '', "platform_name": 'xiaohongshu'})

        medias_release_all_count = 0
        medias_release_count = 0

        views_all_count = 0
        likes_all_count = 0
        collect_all_count = 0

        for item in serializer.data:
            medias_release_all_count += 1
            views_all_count += item['views_count'] if item['views_count'] is not None else 0
            likes_all_count += item['likes_count'] if item['likes_count'] is not None else 0
            collect_all_count += item['collect_count'] if item['collect_count'] is not None else 0
            for plate in companyAdminData:
                if item['platform_name'] == plate['platform_name']:
                    if item['status'] == 3:
                        medias_release_count += 1
                        plate['totalnums'] = plate['totalnums'] + 1
                        plate['nums'] = plate['nums'] + 1
                    else:
                        plate['totalnums'] = plate['totalnums'] + 1


        # # 发布成功数量
        # medias_release_count = medias_release_queryset.filter(status=3).count()
        # # 总发布数量
        # medias_release_all_count = medias_release_queryset.count()

        # # 浏览总量
        # views_all_count = AccountBindMediaContent.objects.all().filter(media_content__in=media_content_ids).aggregate(
        #     total=Sum('views_count'))['total']
        #
        # # 点赞总量
        # likes_all_count = AccountBindMediaContent.objects.filter(media_content__in=media_content_ids).aggregate(
        #     total=Sum('likes_count'))['total']

        # 浏览量排行
        views_count = AccountBindMediaContent.objects.filter(media_content__in=media_content_ids).order_by(
            '-views_count').values()[:7]

        for user in comapny_all_user:
            for media_content in media_content_queryset:
                if user['id'] == media_content['creator_user_id']:
                    user['media_content_id'] = media_content['id']

        for user in comapny_all_user:
            for view in views_count:
                if user['media_content_id'] == view['media_content_id']:
                    view['username'] = user['username'] + str(' -- ') + str(user['first_name'])

        # 点赞排行
        likes_count = AccountBindMediaContent.objects.filter(media_content__in=media_content_ids).order_by(
            '-likes_count').values()[:7]

        # 获取过去一周的第一天和最后一天的日期
        today = timezone.now().date()
        # 获取过去一周的数据数量
        weekly_data_counts = self.get_daily_data_counts(AccountBindMediaContent, today - timedelta(days=7), today)

        # 获取过去三十天的数据数量
        monthly_data_counts = self.get_daily_data_counts(AccountBindMediaContent, today - timedelta(days=30), today)

        # 可以将数据用于其他逻辑处理，例如在模板中显示
        chart_data = {
            'weekly_data': weekly_data_counts,
            'monthly_data': monthly_data_counts,
        }

        result = {
            'comapny_all_user_count': comapny_all_user_count,
            "medias_release_all_count": medias_release_all_count,
            "medias_release_count": medias_release_count,
            "views_all_count": views_all_count,
            "likes_all_count": likes_all_count,
            "views_count": views_count,
            "companyAdminData": companyAdminData,
            "likes_count": likes_count,
            "chart_data": chart_data,
        }

        return APIResponse(results=result)

    @action(methods=['get'], detail=False, url_path='company_staff')
    def company_staff(self, request, *args, **kwargs):
        # 媒体发布
        media_content_queryset = MediaContent.objects.filter(creator_user_id=self.request.user.id).values('id')
        medias_release_queryset = AccountBindMediaContent.objects.filter(media_content__in=media_content_queryset)

        serializer = self.get_serializer(medias_release_queryset, many=True)

        # douyin
        companyStaffData = []
        companyStaffData.append(
            {"id": '1', 'title': '抖音', 'nums': 0, 'totalnums': 0, 'icon': '', "platform_name": 'douyin'})
        companyStaffData.append(
            {"id": '2', 'title': '哔哩哔哩', 'nums': 0, 'totalnums': 0, 'icon': '', "platform_name": 'bilibili'})
        companyStaffData.append(
            {"id": '3', 'title': '快手', 'nums': 0, 'totalnums': 0, 'icon': '', "platform_name": 'kuaishou'})
        companyStaffData.append(
            {"id": '4', 'title': '小红书', 'nums': 0, 'totalnums': 0, 'icon': '', "platform_name": 'xiaohongshu'})

        medias_release_all_count = 0
        medias_release_count = 0

        views_all_count = 0
        likes_all_count = 0
        collect_all_count = 0

        for item in serializer.data:
            medias_release_all_count += 1
            views_all_count += item['views_count'] if item['views_count'] is not None else 0
            likes_all_count += item['likes_count'] if item['likes_count'] is not None else 0
            collect_all_count += item['collect_count'] if item['collect_count'] is not None else 0
            for plate in companyStaffData:
                if item['platform_name'] == plate['platform_name']:
                    if item['status'] == 3:
                        medias_release_count += 1
                        plate['totalnums'] = plate['totalnums'] + 1
                        plate['nums'] = plate['nums'] + 1
                    else:
                        plate['totalnums'] = plate['totalnums'] + 1

        # # 发布成功数量
        # medias_release_count = medias_release_queryset.filter(status=3).count()
        # # 总发布数量
        # medias_release_all_count = medias_release_queryset.count()
        #
        # # 浏览总量
        # views_all_count = \
        #     AccountBindMediaContent.objects.all().filter(media_content__in=media_content_queryset).aggregate(
        #         total=Sum('views_count'))['total']
        #
        # # 点赞总量
        # likes_all_count = AccountBindMediaContent.objects.filter(media_content__in=media_content_queryset).aggregate(
        #     total=Sum('likes_count'))['total']
        #
        # # 浏览总量
        # collect_all_count = AccountBindMediaContent.objects.filter(media_content__in=media_content_queryset).aggregate(
        #     total=Sum('collect_count'))['total']

        # 浏览量排行
        views_count = AccountBindMediaContent.objects.filter(media_content__in=media_content_queryset).order_by(
            '-views_count').values()[:7]

        # 点赞排行
        likes_count = AccountBindMediaContent.objects.filter(media_content__in=media_content_queryset).order_by(
            '-likes_count').values()[:7]

        # 收藏排行
        collect_count = AccountBindMediaContent.objects.filter(media_content__in=media_content_queryset).order_by(
            '-collect_count').values()[:7]

        # 获取过去一周的第一天和最后一天的日期
        today = timezone.now().date()
        # 获取过去一周的数据数量
        weekly_data_counts = self.get_daily_data_counts(AccountBindMediaContent, today - timedelta(days=7), today)

        # 获取过去三十天的数据数量
        monthly_data_counts = self.get_daily_data_counts(AccountBindMediaContent, today - timedelta(days=30), today)

        # 可以将数据用于其他逻辑处理，例如在模板中显示
        chart_data = {
            'weekly_data': weekly_data_counts,
            'monthly_data': monthly_data_counts,
        }

        result = {
            "medias_release_all_count": medias_release_all_count,
            "medias_release_count": medias_release_count,
            "views_all_count": views_all_count,
            "likes_all_count": likes_all_count,
            "collect_all_count": collect_all_count,
            "views_count": views_count,
            "likes_count": likes_count,
            "companyStaffData": companyStaffData,
            "collect_count": collect_count,
            "chart_data": chart_data,
        }

        return APIResponse(results=result)
